<?php

namespace Post\Model;

use Carbon\Carbon;
use Common\Model\BaseModel;
use Biz\AliyunLive;
use Common\Model\ModelException;

class GiftModel extends BaseModel
{
    protected $_scope = [
        'valid' => [
            'where' => ['delete_time' => 0],
        ]
    ];

    public function publish($uid, $data)
    {
        if (!$uid) throw new ModelException(80001, '发布人不能为空');
        $post = [
            'user_id' => $uid,
            'details' => $data['details'],
            'pic' => $data['pic'] ?: '',
            'video' => $data['video'] ?: '',
            'type' => $data['type'],
            'audit' => 1, // 默认
        ];

        $postModel = D('Post');
        if ($a= $postModel->create($post)) {
            $id = $postModel->add();
            $post = D('Post')->find($id);
            tag('publish_post', $post);
            return $id;
        } else {
            throw new ModelException(80001, $postModel->getError());
        }
    }

    public function praise($postId, $userId)
    {
        $zan = D('PostZan')->where(['post_id' => $postId, 'user_id' => $userId])->find();
        if ($zan) {
            throw new ModelException(80002);
        }
        D('Post')->where(['post_id' => $postId])->setInc('zan_num', 1);
        D('PostZan')->add([
            'post_id' => $postId,
            'user_id' => $userId,
            'create_time' => time(),
            'create_ip' => get_client_ip(),
        ]);
        return true;
    }

    protected function _after_find(&$record, $options)
    {
        $config = C('sdk.oss');
        $user = get_user();
        if ($record['pic']){
            $pics = explode(',', $record['pic']);
            $record['pic'] = array_map(function($pic) use ($config) {
                return oss_images_auto_fill($pic, $config['styles']);
            } , $pics);
        } else {
            $record['pic'] = [];
        }
        if ($record['video']) {
            $media = D('Helper/Media')->where(['url' => $record['video']])->find();
            if ($media) {
                $record['cover_url'] = $media['cover_url'] . '?x-oss-process=style/video_cover';
            }
            if (isset($config['cdn'])) {
                $record['video'] = str_replace($config['bucket'] . '.' . $config['endpoint'], $config['cdn'], $record['video']);
            }

        }
        if ($record['create_time']) {
            Carbon::setLocale('zh');
            $record['human_time'] = Carbon::createFromTimestamp($record['create_time'])->diffForHumans();
        }
        $zanPostIds = D('PostZan')->where(['user_id' => $user['id']])->getField('post_id', true);
        $record['is_zan'] = in_array($record['post_id'], $zanPostIds) ? 1 : 0;
    }

    protected function _after_select(&$records, $options)
    {
        if (empty($records)) return;
        $user = get_user();
        $zanPostIds = D('PostZan')->where(['user_id' => $user['id']])->getField('post_id', true);
        Carbon::setLocale('zh');
        $config = C('sdk.oss');

        /* 查询动态中包含的video信息 */
        $videos = array_column($records, 'video');
        
        if ($videos) {
            $medias = D('Helper/Media')->where(['url' => ['in', $videos]])->select();
            $mediasDict = array_column($medias, null, 'url');
        }

        foreach ($records as &$record) {
            if ($record['pic']){
                $pics = explode(',', $record['pic']);
                
                $record['pic'] = array_map(function($pic) use ($config) {
                    return oss_images_auto_fill($pic, $config['styles']);
                } , $pics);
            } else {
                $record['pic'] = [];
            }
            if ($record['create_time']) {
                
                $record['human_time'] = Carbon::createFromTimestamp($record['create_time'])->diffForHumans();
            }
            if ($record['video']) {
                if ($mediasDict && isset($mediasDict[$record['video']])) {
                    // 固定样式
                    $record['cover_url'] = $mediasDict[$record['video']]['cover_url'] ? $mediasDict[$record['video']]['cover_url'] . '?x-oss-process=style/video_cover' : '';
                }
                if (isset($config['cdn'])) {
                    $record['video'] = str_replace($config['bucket'] . '.' . $config['endpoint'], $config['cdn'], $record['video']);
                }
            }
            $record['is_zan'] = in_array($record['post_id'], $zanPostIds) ? 1 : 0;
        }
    }

    protected function implodeImage($images)
    {
        return $images ? implde(',', $images) : '';
    }
}
